package com.sergiandreplace.walkshop.server.servlet;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sergiandreplace.walkshop.server.domain.Walkeet;
import com.sergiandreplace.walkshop.server.model.WalkeetModel;
import com.sergiandreplace.walkshop.server.servlet.message.ResponseMessage;

@SuppressWarnings("serial")

public class WalkeetServlet extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{

		WalkeetModel model = new WalkeetModel();
		ResponseMessage message;
		resp.setContentType("application/json");
		int firstResult=0;
		int maxResults=20;

		if (req.getParameterMap().containsKey("id")) {
			Walkeet walkeet=model.getWalkeet(Integer.parseInt(req.getParameter("id")));
			if (walkeet==null) {
				message=new ResponseMessage("KO", "Id not found");
				resp.setStatus(404);
				resp.getWriter().write(message.toJson());
				return; 
			}
			message=new ResponseMessage("OK", walkeet);
			resp.getWriter().write(message.toJson());
			return; 
		}else{
			if (req.getParameterMap().containsKey("firstResult")) {
				firstResult=Integer.parseInt(req.getParameter("firstResult"));
			}
			if (req.getParameterMap().containsKey("maxResults")) {
				maxResults=Integer.parseInt(req.getParameter("maxResults"));
			}
			List<Walkeet> walkeets = model.getWalkeets(firstResult, maxResults);
			message=new ResponseMessage("OK", walkeets);
			resp.getWriter().write(message.toJson());
			return; 
		}
		
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		Walkeet walkeet;
		ResponseMessage message;
		resp.setContentType("application/json");
		ObjectMapper mapper=new ObjectMapper();
		try {
			walkeet=mapper.readValue(req.getReader(), Walkeet.class) ;
		}catch (Exception e) {
			message=new ResponseMessage("KO", e.getMessage());
			resp.setStatus(400);
			resp.getWriter().write(message.toJson());
			return;
		}
		if (!walkeet.isOk()) {
			message=new ResponseMessage("KO", "Wrong data");
			resp.setStatus(400);
			resp.getWriter().write(message.toJson());
			return;
		}

		walkeet.setToken(UUID.randomUUID().toString());


		try {	
			WalkeetModel.insert(walkeet);
		} catch (Exception e) {
			message=new ResponseMessage("KO", e.getMessage());
			resp.setStatus(400);
			resp.getWriter().write(message.toJson());
			return;
		}

		message=new ResponseMessage("OK",walkeet);
		resp.setStatus(200);
		resp.getWriter().write(message.toJson());

	}
}